/*
 *  Class name: PlayerCriteriaQueryBuilder.java
 *  Version: 1.0
 *  Date: 19.2.2014
 */
package cz.muni.fi.pa165.soccergamesarchive.persistencelayer.querybuilders.entity;

import cz.muni.fi.pa165.soccergamesarchive.persistencelayer.entities.Player;
import cz.muni.fi.pa165.soccergamesarchive.persistencelayer.querybuilders.EntityCriteriaQueryBuilder;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Root;

/**
 *
 * @author Michal Ďuriš
 */
public class PlayerCriteriaQueryBuilder extends EntityCriteriaQueryBuilder<Player> {

    public PlayerCriteriaQueryBuilder(Class<Player> entityClass) {
        super(entityClass);
    }

    @Override
    protected Expression<Boolean> getFieldFilterExpression(String propertyName,
                                                           CriteriaBuilder criteriaBuilder,
                                                           Root<Player> entityRoot) {

        Expression<Boolean> fieldFilterExpression;

        if (propertyName == null || propertyName.isEmpty()) {

            return null;
        }

        switch (propertyName) {
            case "homeTeam":
            case "awayTeam":
                fieldFilterExpression = criteriaBuilder.equal(entityRoot
                        .join("team").get("id").as(Long.class),
                        criteriaBuilder.parameter(Long.class, propertyName));
                break;
            case "team":
                fieldFilterExpression = criteriaBuilder.like(criteriaBuilder
                        .lower(entityRoot.join("team").get("name").as(
                                        String.class)),
                        criteriaBuilder.parameter(String.class, propertyName));
                break;
            default:
                fieldFilterExpression = criteriaBuilder.like(criteriaBuilder
                        .lower(entityRoot.get(propertyName).as(String.class)),
                        criteriaBuilder.parameter(String.class, propertyName));
                break;
        }

        return fieldFilterExpression;
    }

    @Override
    protected Expression<?> getFieldOrderExpression(String propertyName,
                                                    Root<Player> entityRoot) {

        if (propertyName == null || propertyName.isEmpty()) {
            return null;
        }

        switch (propertyName) {
            case "team":
                return entityRoot.join("team").get("name");
            default:
                return entityRoot.get(propertyName);
        }
    }

}
